<template>
  <div class="container">
    <!-- 药品清单表格 -->
    <el-table :data="medicines" style="width: 95%" border>
      <el-table-column label="药品名" prop="name" width="250" />
      <el-table-column label="规格" prop="specifications" width="250" />
      <el-table-column label="类型" prop="type" width="150" />
      <el-table-column label="类别" prop="category" width="146" />
      <el-table-column label="药品剂型" prop="dosage" width="150" />
      <el-table-column label="使用方法" prop="usage" width="120" />
      <el-table-column label="价格（元）" prop="price" width="100" />
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click="showPurchaseModal(scope.row)" type="primary">购买</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看已购买药品按钮 -->
    <el-button @click="showPurchasedMedicines" type="success" style="margin-top: 20px;">
      查看已购买药品
    </el-button>

    <!-- 购买药品弹窗 -->
    <el-dialog title="购买药品" :visible.sync="isModalVisible" width="400px">
      <el-form :model="form">
        <el-form-item label="药品名" :label-width="formLabelWidth">
          <el-input v-model="selectedMedicine.name" disabled />
        </el-form-item>
        <el-form-item label="药品规格" :label-width="formLabelWidth">
          <el-input v-model="selectedMedicine.specifications" disabled />
        </el-form-item>
        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-input v-model="selectedMedicine.type" disabled />
        </el-form-item>
        <el-form-item label="使用方法" :label-width="formLabelWidth">
          <el-input v-model="selectedMedicine.usage" disabled />
        </el-form-item>
        <el-form-item label="购买数量" :label-width="formLabelWidth">
          <el-input-number v-model="purchaseQuantity" :min="1" :step="1" @change="updateTotalPrice" />
        </el-form-item>
        <el-form-item label="总价" :label-width="formLabelWidth">
          <el-input v-model="totalPrice" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handlePurchase">确认购买</el-button>
      </div>
    </el-dialog>

    <!-- 已购买药品弹窗 -->
    <el-dialog title="已购买药品" :visible.sync="isPurchasedModalVisible" width="860px">
      <el-table :data="purchasedMedicines" style="width: 100%" border>
        <el-table-column label="药品名" prop="name" width="200" />
        <el-table-column label="规格" prop="specifications" width="200" />
        <el-table-column label="价格（元）" prop="price" width="100" />
        <el-table-column label="购买数量" prop="number" width="80" />
        <el-table-column label="总价" prop="totalPrice" width="80" />
        <el-table-column label="购买时间" prop="createdTime" width="160" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handlePurchasedCancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MedicineList',
  data() {
    return {
      medicines: [],  // 药品列表
      isModalVisible: false,  // 控制购买弹窗的显示
      isPurchasedModalVisible: false,  // 控制已购买药品弹窗的显示
      selectedMedicine: {},  // 当前选中的药品
      purchaseQuantity: 1,  // 购买数量
      totalPrice: 0,  // 总价
      purchasedMedicines: [],  // 已购买药品列表
      form: {},
      formLabelWidth: '100px',  // 表单label宽度
    };
  },
  methods: {
    // 显示购买弹窗
    showPurchaseModal(medicine) {
      this.selectedMedicine = { ...medicine };
      this.totalPrice = medicine.price * this.purchaseQuantity;
      this.isModalVisible = true;
    },

    // 处理购买
    handlePurchase() {
      console.log(`购买药品: ${this.selectedMedicine.name}`);
      console.log(`购买数量: ${this.purchaseQuantity}`);
      console.log(`总价: ${this.totalPrice}`);
      // 购买药品的API请求
      this.$axios({
        url: 'purchaseDrugs',
        method: 'post',
        data: {
          medicineId: this.selectedMedicine.id,
          number: this.purchaseQuantity,
          phone: this.$session.get('phone'),
        },
      }).then(res => {
        console.log('购买成功:', res.data);
        this.$message.success('购买成功');
        // 关闭购买弹窗
        this.isModalVisible = false;
      }).catch(error => {
        this.$message.error('购买失败');
        console.error(error);
      });
    },

    // 取消购买
    handleCancel() {
      this.isModalVisible = false;
    },

    // 更新总价
    updateTotalPrice() {
      this.totalPrice = this.selectedMedicine.price * this.purchaseQuantity;
    },

    // 初始化药品列表
    fetchMedicines() {
      this.$axios({
        url: 'getMedicine',  // 获取药品数据的API
        method: 'get',
      }).then(res => {
        this.medicines = res.data;
      }).catch(error => {
        console.error('获取药品数据失败:', error);
      });
    },

    // 查看已购买药品
    showPurchasedMedicines() {
      this.$axios({
        url: 'getPurchasedMedicines',  // 获取已购买药品数据的API
        method: 'get',
        params: { phone: this.$session.get('phone') }  // 传递用户的手机号或其他标识
      }).then(res => {
        this.purchasedMedicines = res.data;
        // 为其计算总价.并格式化时间
        this.purchasedMedicines.forEach(medicine => {
          medicine.totalPrice = medicine.price * medicine.number;
          medicine.createdTime = new Date(medicine.createdTime).toLocaleString();
        });
        this.isPurchasedModalVisible = true;
      }).catch(error => {
        this.$message.error('获取已购买药品失败');
        console.error(error);
      });
    },

    // 关闭已购买药品弹窗
    handlePurchasedCancel() {
      this.isPurchasedModalVisible = false;
    }
  },
  mounted() {
    this.fetchMedicines();  // 页面加载时获取药品列表
  },
};
</script>

<style scoped>
/* 容器居中 */
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  /*height: 100vh;*/
  margin: 0;
}

/* 药品表格样式 */
.el-table {
  margin-top: 30px;
  width: 80%;
  margin-bottom: 20px;
}

/* 弹窗样式 */
.purchase-dialog {
  width: 400px;
}
</style>
